package com.example.rocketmqdemo.transaction.infr.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.rocketmqdemo.transaction.domain.gateway.LoginUserGateway;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充处理类
 **/
@Component
public class MybatisPulsMetaObjectHandler implements MetaObjectHandler {

    public static final String FIELD_IS_DELETE = "isDelete";
    public static final String FIELD_CREATE_TIME = "createTime";
    public static final String FIELD_UPDATE_TIME = "updateTime";
    public static final String FIELD_CREATE_BY = "createBy";
    public static final String FIELD_UPDATE_BY = "updateBy";

    @Autowired
    private LoginUserGateway loginUserGateway;

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(FIELD_IS_DELETE)) {
            this.strictInsertFill(metaObject, FIELD_IS_DELETE, Boolean.class, false);
        }
        if (metaObject.hasSetter(FIELD_CREATE_TIME)) {
            this.strictInsertFill(metaObject, FIELD_CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (metaObject.hasSetter(FIELD_UPDATE_TIME)) {
            this.strictInsertFill(metaObject, FIELD_UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (metaObject.hasSetter(FIELD_CREATE_BY)) {
            this.strictInsertFill(metaObject, FIELD_CREATE_BY, String.class, loginUserGateway.getUsername());
        }
        if (metaObject.hasSetter(FIELD_UPDATE_BY)) {
            this.strictInsertFill(metaObject, FIELD_UPDATE_BY, String.class, loginUserGateway.getUsername());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(FIELD_UPDATE_TIME)) {
            this.strictInsertFill(metaObject, FIELD_UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (metaObject.hasSetter(FIELD_UPDATE_BY)) {
            this.strictInsertFill(metaObject, FIELD_UPDATE_BY, String.class, loginUserGateway.getUsername());
        }
    }
}
